<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Shop extends CI_Controller {
	
	function __construct(){
		parent::__construct();
		//$this->js->alert('暂未开放');
		//$this->js->go('/');
	}
	
	function shop_gonggao(){
		$this->load->model('site_model');
		$site = $this->site_model->get_site_one(array('url'=>'shop'));
		
		if($site['id'] > 0){
			$cdata['where']['nid'] = $site['id'];	
			$cdata['page_size']  = 7;
			$cdata['page_start'] = 0;
			$cdata['select'] 	= 1;
			$this->load->model('article_model');
			$nret = $this->article_model->get_article_list($cdata);
			$shop_notices = $nret['article_list'];
		}
		
		return $shop_notices;
		
	}
	
	function shop_hot_product(){
		$pdata = array(
			'page' => 0,
			'page_size' => 25,
			'where' => array('pstatus' => 1, 'phot' => 1),
		);
		$ret = $this->Shop_model->pageData($pdata);
		
		$hot_list = $ret['list'];
		return $hot_list;
	}
	
	function index(){
		
		//获取公告
		
		$vdata['shop_notices'] = $this->shop_gonggao();
		
		$this->load->model('Shop_model');
		
		//推荐商品列表
		$pdata = array(
			'page' => 0,
			'page_size' => 3,
			'where' => array('pstatus' => 1, 'ptui' => 1),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['tui_list'] = $ret['list'];
		
		//办公类
		$pdata = array(
			'page' => 0,
			'page_size' => 6,
			'where' => array('pstatus' => 1, 'ptype' => 1),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['type1_list'] = $ret['list'];
		
		//电子类
		$pdata = array(
			'page' => 0,
			'page_size' => 6,
			'where' => array('pstatus' => 1, 'ptype' => 2),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['type2_list'] = $ret['list'];
		
		//生活类
		$pdata = array(
			'page' => 0,
			'page_size' => 6,
			'where' => array('pstatus' => 1, 'ptype' => 3),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['type3_list'] = $ret['list'];
		
		//秒杀
		$pdata = array(
			'page' => 0,
			'page_size' => 1,
			'where' => array('pstatus' => 1, 'prob' => 1),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['rob_list'] = $ret['list'];
		
		//团购
		$pdata = array(
			'page' => 0,
			'page_size' => 4,
			'where' => array('pstatus' => 1, 'ptuan' => 1),
		);
		$ret = $this->Shop_model->pageData($pdata);
		$vdata['tuan_list'] = $ret['list'];
		
		
		//火热
		$vdata['hot_list'] = $this->shop_hot_product();
		
		
		//滚动图片
		$this->load->model('scrollpic_model');
		$vdata['scrollpic_list'] = $this->scrollpic_model->get_shop_scrollpic_list_index();
		
		//商城公告
		$vdata['product_notice_list'] = $this->Shop_model->get_shop_order_show_index();
		
		$vdata['vars'] = $this->Shop_model->arrays();
		$vdata['title'] = '华银资本-积分商城';
		$this->load->view('shop/index',$vdata);
	}
	
	function car(){
		$user = $this->session->userdata('zjy_user');
		if (isset($user['user_id']) && $user['user_id']>0){
			$pid = intval($this->input->post('pid'));
			$pnum = intval($this->input->post('pnum'));
			$pnum = max(1,$pnum);
			$user_id = $user['user_id'];
			$this->load->model('Shop_model');
			$this->load->model('Credit_model');
			$info = $this->Shop_model->getOne($pid);
			$data['info'] = $info;
			$last_order = $this->Shop_model->getLastOrder($user_id);
			$data['last_order'] = $last_order;
			$credit = $this->Credit_model->get_row($user_id);
			$data['credit'] = $credit;
			$data['num'] = $pnum;
			$data['title'] = '德益投资-积分商城';
			$this->load->view('shop/shop_car',$data);
		}else{
			$this->js->go('/login.html');
		}
	}
	
	function buy(){
		$ret = array(
			'msg' => '数据错误',
			'url' => '/shop/index.html'
		);
		
		
		/*if (time()>=strtotime('2014-01-21')){
			$ret['msg'] = '您好，春节因为快递公司休息，受此影响，期间商城暂停开放，年后商城会重新开放！';
			echo json_encode($ret);
			exit;
		}*/
		
		$user = $this->session->userdata('zjy_user');
		if (isset($user['user_id']) && $user['user_id']>0){
			$user_id = $user['user_id'];
			$now = time();
			$pid = intval($this->input->post('pid'));
			$pnum = intval($this->input->post('pnum'));
			$this->load->model('Shop_model');
			$this->load->model('Credit_model');
			$this->load->model('User_vip_model');
			
			$pinfo = $this->Shop_model->getOne($pid);
			if ($pinfo['pstatus'] != 1){
				$ret['msg'] = '该商品已下架';
				echo json_encode($ret);
				exit;
			}
			if ($pnum<1){
				$ret['msg'] = '数据错误';
				echo json_encode($ret);
				exit;
			}
			$credit = $this->Credit_model->get_row($user_id);
			$vipinfo = $this->User_vip_model->get_by_uid($user_id);
			$isVip = false;
			if (isset($vipinfo['vip_status']) && $vipinfo['vip_status'] == 1 && $vipinfo['vip_verify_time']+3600*24*365>$now){
				$isVip = true;
				$totalPrice = $pinfo['pvipcredit']*$pnum;
			}else{
				$totalPrice = $pinfo['pcredit']*$pnum;
			}
			if ($pinfo['pvip']==1 && $isVip==false){
				$ret['msg'] = '该商品只有VIP才能兑换';
				echo json_encode($ret);
				exit;
			}
			if ($pinfo['prob']==1 && $pinfo['probstart']>$now){
				$ret['msg'] = '该商品起售时间为'.date('Y-m-d H:i:s',$pinfo['probstart']);
				echo json_encode($ret);
				exit;
			}
			
			if (!isset($credit['available']) || $totalPrice>$credit['available']){
				$ret['msg'] = '积分不足';
				echo json_encode($ret);
				exit;
			}
			
			/*$monthCost = $this->Shop_model->getMonthCost($user_id);
			if ($monthCost+$totalPrice>20000){
				$ret['msg'] = '30天内兑换不能超出20000分';
				echo json_encode($ret);
				exit;
			}*/
			
			if ($pnum>$pinfo['psurp']){
				$ret['msg'] = '库存不足';
				echo json_encode($ret);
				exit;
			}
//			$this->load->model('Account_model');
//			$accInfo = $this->Account_model->get_account($user_id);
//			if ($accInfo['collection']<20000){
//				$ret['msg'] = '待收金额不足';
//				echo json_encode($ret);
//				exit;
//			}
			
			$isLast = $this->input->post('last_address');
			if ($isLast==1){
				$last_order = $this->Shop_model->getLastOrder($user_id);
				$getName = $last_order['get_name'];
				$getAddress = $last_order['get_address'];
				$getPhone = $last_order['get_phone'];
				$getPc = $last_order['get_pc'];
			}else{
				$getName = $this->input->post('get_name');
				$getAddress = $this->input->post('get_address');
				$getPhone = $this->input->post('get_phone');
				$getPc = $this->input->post('get_pc');
			}
			$setArr = array(
				'user_id' => $user_id,
				'pid' => $pid,
				'pnum' => $pnum,
				'price' => $pinfo['pcredit'],
				'total_price' => $totalPrice,
				'get_name' => $getName,
				'get_address' => $getAddress,
				'get_phone' => $getPhone,
				'get_pc' => $getPc,
				'add_time' => time(),
			);
			foreach ($setArr as $v){
				if (!$v){
					$ret['msg'] = '数据错误';
					$ret['url'] = '';
					echo json_encode($ret);
					exit;
				}
			}
			
			//扣除积分
			$log = array(
				'user_id'=>$user_id,
				'type_id'=>16,
				'op' => 2,
				'credit_value' => $totalPrice,
				'remark' => '商城兑换',
				'op_user'=>1,
				'add_time'=>time(),
				'addip'=>$this->input->ip_address()
			);
			$res = $this->Credit_model->decr_credit($log);
			if ($res){
				$res = $this->Shop_model->addOrder($setArr);
				if ($res){
					$upArr = array(
						'pconvert'=>$pinfo['pconvert']+$pnum,
						'psurp' => $pinfo['psurp']-$pnum,
					);
					$res = $this->Shop_model->update($upArr,array('id'=>$pid));
				}
			}
            if($res){
                //发送积分兑换成功站内信
                $this->load->model('Message_model');
                $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $user_id,
                    'name' => "恭喜您积分兑换{$pinfo['pname']}成功，我们即可为您安排。",
                    'fstatus' => 0,
                    'message_type' => 'system',
                    'sented' => 0,
                    'deltype' => 0,
                    'content' => "恭喜您积分兑换{$pinfo['pname']}成功，我们即可为您安排。",
                    'add_time' => time(),
                    'addip' => $this->js->get_ip()
                ));
            }
			$ret['msg'] = $res ? '兑换成功' : '兑换失败';
			$ret['url'] = '/shop/index.html';
			echo json_encode($ret);
			exit;
		}else{
			$ret['msg'] = '请先登录';
			$ret['url'] = '/login.html';
			echo json_encode($ret);
			exit;
		}
	}
	
	function info($id=''){
		$id = intval($id);
		//echo $id;
		$this->load->model('Shop_model');
		$vdata['info'] = $this->Shop_model->getOne($id);
		//var_dump($vdata['info']);exit;
		$data = array(
			'page' => 0,
			'page_size'=>999,
			'order' => 'add_time',
			'where' => array(
				'pid' => $id
			)
		);
		$ret = $this->Shop_model->orderPageList($data);
		$vdata['olist'] = $ret['list'];
		
		
		//火热
		$vdata['hot_list'] = $this->shop_hot_product();
		
		//获取公告
		$vdata['shop_notices'] = $this->shop_gonggao();

        //商品图片
        $vdata['att_list'] = $this->Shop_model->get_list_shop_pic($id);
		
		$vdata['title'] = '德益投资-积分商城';
//		$types_arr = $this->Shop_model->arrays('types');
//		$vdata['subtab'] = $types_arr[$vdata['info']['ptype']];
//        $vdata['obj'] = $this->Shop_model->get_shop_type_obj($vdata['info']['ptype']);
        $vdata['parents'] = $this->Shop_model->get_parent_list($vdata['info']['ptype'],array());
		
		$this->load->view('shop/shop_list_con',$vdata);
	}
	
	function arr(){
		$per_page  = intval($this->input->get('per_page'));
		$page_size = 12;
		
		
		$this->load->model('Shop_model');
        $ptype = intval($this->input->get('ptype'));
        //获取三级级子孙内及自己的id
        $child_ids = $this->Shop_model->get_child_ids(intval($ptype));
        $child_ids = implode(',',$child_ids);

//		$where['ptype'] = intval($this->input->get('ptype'));
        $where['ptypes'] = $child_ids;
		$where['ptui'] = intval($this->input->get('tui'));
		$where['ptuan'] = intval($this->input->get('tuan'));
		$where['phot'] = intval($this->input->get('hot'));
		$where['prob'] = intval($this->input->get('rob'));
		$where['pvip'] = intval($this->input->get('vip'));
		
		$tmp = array();
		foreach ($where as $k => $v){
			if ($v){
				$tmp[] = $k.'='.$v;
			}
		}
		$tmpUrl = implode('&', $tmp);
		
		$where['pstatus'] = 1;
		$pdata = array(
			'page' => $per_page,
			'page_size' => $page_size,
			'where' => $where,
		);
		$data = $this->Shop_model->pageData($pdata);
//        var_dump($data);exit;

        //获取该分类下的子分类名称
        $data['child_list'] = $this->Shop_model->get_shop_category_by_pid($ptype);
		
		$this->load->library('pagination');
		
		
		$config['base_url'] = '/shop/arr.html?'.$tmpUrl;
		$config['total_rows'] = $data['count'];
		$config['per_page'] = $page_size; 
		$this->pagination->initialize($config); 
		//火热
		
		$data['hot_list'] = $this->shop_hot_product();
		$data['vars'] = $this->Shop_model->arrays();
		
		//获取公告
		
		$data['shop_notices'] = $this->shop_gonggao();
		
//		$types_arr = $this->Shop_model->arrays('types');
//        $data['subtab'] = $types_arr[$where['ptype']];
        $data['obj'] = $this->Shop_model->get_shop_type_obj($ptype);
        $data['parents'] = $this->Shop_model->get_parent_list($ptype,array());
		$data['title'] = '德益投资-积分商城';
		$this->load->view('shop/shop_list',$data);
	}
	
	
	function box(){
		$this->load->model('Shop_model');
		$data = array(
			'page'=>0,
			'page_size' => 20,
			'order'=>'add_time',
			'is_index' => 1,
			'where'=>array(
				'is_open' => 1,
			)
		);
		//$ret = $this->Shop_model->getBoxList($data);
		$mkey = 'box_notices';
		$notices = $this->mycache->get_array($mkey);
		//var_dump($notices);exit;
		$notices = $notices ? $notices : array();
		$vdata['list'] = $notices;//$ret['list'];
		$vdata['title'] = '德益投资-积分商城';
		/*$productArr = array(
			'1010'=>'30元电话卡',
			'1013'=>'壹投资VIP会员（半年）',
			'1014'=>'壹投资VIP会员（三个月）',
			'1015'=>'壹投资VIP会员（一个月）',
		);*/
		//$vdata['plist'] = $productArr;
		
		//$strtime = date('2014-4-28 10:00:00');
		$strtime = date('Y-m-d')." 00:00:00";
		$boxdata['where'] = array('is_open'=>1,'strtime'=>$strtime);
		$boxlist = $this->Shop_model->getBoxList($boxdata);
		$vdata['total'] = $boxlist['count'];
		
		for($i=1;$i<6;$i++){
			$colordata['where'] = array('box_color'=>$i,'is_open'=>1,'strtime'=>$strtime);
			$color = $this->Shop_model->getBoxList($colordata);
			$colorlist[$i] = $color['count'];
		}
		
		$vdata['color_box'] = $colorlist;
		//$this->mycache->delete('box_specific');
		$specific = $this->award_cache();
		$vdata['specific_list'] = $specific;
        //获取用户数据
        $CI = & get_instance();
        $CI->load->model('header_model');
        $vdata['hdata'] = $CI->header_model->show();
		
		$this->load->view('shop/shopact',$vdata);
	}
	
	function openlist(){
		
		
	}
	
	function open(){
		$ret = array(
			'msg' => '数据错误',
			'succ' => 0,
			'color' => 0
		);
		$user = $this->session->userdata('zjy_user');
		if (isset($user['user_id']) && $user['user_id']>0){
			$user_id = $user['user_id'];
			$this->load->model('User_vip_model');
			//用户可以抽几次
			$isVip = $this->User_vip_model->is_vip($user_id);
			$MyCount = $isVip ? 3 : 10;//VIP1天3次  非VIP1天1次
			//今天抽过几次
			$this->load->model('Shop_model');
//			$todayCount = $this->Shop_model->getTodayBoxNum($user_id);
//			if ($todayCount>=$MyCount && $user['user_id']!=226){
//				$ret['msg'] = '今日抽奖次数已用完';
//				echo json_encode($ret);
//				exit;
//			}else{
				
				/*if (time()>strtotime('2014-04-01')){//!in_array($user_id, array(226,1205,2262)) && 
					$ret['msg'] = '暂未开放';
					echo json_encode($ret);
					exit;
				}*/
				
				//随机盒子颜色
				$colorRate = array(
					1=>5, //金
					2=>10,//银
					3=>30,//铜
					4=>30,//铁
					5=>25,//木
				);
				//开盒子消耗积分
				$colorCost = array(
					1=>2502, //金
					2=>1502,//银
					3=>802,//铜
					4=>502,//铁
					5=>32,//木
				);
				$colorText = array(1=>'金',2=>'银',3=>'铜',4=>'铁',5=>'木');
				$this->load->library('func');
				$color = $this->func->dice($colorRate);
				/*if ($user_id==226){
					$color  = 1;
				}*/
				$cost = $colorCost[$color];//打开箱子需要消耗的积分
				//初始化盒子
				$boxData = array(
					'user_id' => $user_id,
					'box_color' => $color,
					'open_credit' => $cost,
					'add_time' => time(),
				);
				$boxId = $this->Shop_model->initBox($boxData);
				
				$msg = "恭喜您抽中 ".$colorText[$color]." 聚宝盆，你要花费".$cost."积分打开吗？";
				if ($boxId){
					$ret['msg'] = $msg;
					$ret['succ'] = $boxId;
					$ret['color'] = $color;
					echo json_encode($ret);
					exit;
				}else{
					$ret['msg'] = "再接再厉";
					echo json_encode($ret);
					exit;
				}
				
//			}
		}else{
			$ret['msg'] = '请先登录';
			echo json_encode($ret);
			exit;
		}
	}
	
	function doopen(){
		$user = $this->session->userdata('zjy_user');
		$result['msg'] = '';
		$result['succ'] = 0;
		$result['data'] = '';
		if (isset($user['user_id']) && $user['user_id']>0){
			$user_id = $user['user_id'];
			$boxId  = intval($this->input->get('bid'));
			if ($boxId>0){
				$this->load->model('Shop_model');
				$this->load->model('Credit_model', 'credit');
				$boxInfo = $this->Shop_model->getBox($boxId);
				$colorText = array(1=>'金',2=>'银',3=>'铜',4=>'铁',5=>'木');
				if ($boxInfo['user_id']==$user_id){
					//$boxInfo['award_type']==4 && 
					if ($boxInfo['award_type']!=4 && time()>$boxInfo['add_time']+3600){
						//echo "已过期的宝箱";
						$result['msg'] = '已过期的宝箱';
						echo json_encode($result);
						exit;
					}else{
						//各种颜色箱子打开所需积分
						$this->load->model('Credit_model');
						$myCredit = $this->Credit_model->get_row($user_id);
						$myAvailable = isset($myCredit['available']) ? $myCredit['available'] : 0;
						$cost = $boxInfo['open_credit'];
						if ($boxInfo['award_type']==4){
							if ($boxInfo['miss_time']>time()){
								$cost = 0;
							}else{
								$result['msg'] = '钥匙已过期';
								echo json_encode($result);
								exit;
							}
							
						}
						if ($cost>$myAvailable){
							//echo "积分不足";
							$result['msg'] = '积分不足';
							echo json_encode($result);
							exit;
						}
						
						//扣除积分
						if ($cost>0){
							$log = array(
								'user_id'=>$user_id,
								'type_id'=>16,
								'op' => 2,
								'credit_value' => $cost,
								'remark' => '打开宝箱',
								'op_user'=>1,
								'add_time'=>time(),
								'addip'=>$this->input->ip_address()
							);
							$res = $this->Credit_model->decr_credit($log);
							if (!$res){
								//echo "打开宝箱失败";
								$result['msg'] = '打开宝箱失败';
								echo json_encode($result);
								exit;
							}
						}
						
						
						//各颜色箱子出奖概率
						$boxAwardRate = array(
							//金
							'1' => array(
								1=>5,//1等
								2=>70,//2等
								3=>20,//3等
								4=>5, //4等
							),
							//银
							'2' => array(
								1=>5,//1等
								2=>40,//2等
								3=>50,//3等
								4=>5, //4等
							),
							//铜
							'3' => array(
								1=>5,//1等
								2=>40,//2等
								3=>50,//3等
								4=>5, //4等
							),
							//铁
							'4' => array(
								1=>5,//1等
								2=>40,//2等
								3=>50,//3等
								4=>5, //4等
							),
							//木
							'5' => array(
								1=>15,//1等
								2=>25,//2等
								3=>55,//3等
								4=>5, //4等
							),
						);
						//奖品设置
						//积分奖励   颜色_几等=>奖励积分数量
						$creditAward = array(
							'1_3'=>array(1088,1888),//金色3奖
							'2_3'=>array(888,1088),//银色3奖
							'3_3'=>array(388,588), //铜色3奖
							'4_3'=>array(188,388), //铁色3奖
							'5_1'=>array(32,42),  //木色1奖
							'5_3'=>array(28,30)  //木色1奖
						);
						$productArr = array(
							'1002'=>'青花U盘（4G）',
							'1003'=>'青花移动电源',
							'1005'=>'青花名片夹',
							'1008'=>'100元电话卡',
							'1010'=>'30元电话卡',
							'1013'=>'德益投资VIP会员（半年）',
							'1014'=>'德益投资VIP会员（三个月）',
							'1015'=>'德益投资VIP会员（一个月）',
							'1019'=>'金钥匙',
							'1020'=>'银钥匙',
							'1021'=>'铜钥匙',
							'1022'=>'铁钥匙',
							'1023'=>'木钥匙',
						);
						
					
						//商品奖励
						$productAward = array(
							'1_1'=>'1008',//商品ID
							//'1_2'=>'1019',
							'2_1'=>'1003',
							//'2_2'=>'1020',
							'3_1'=>'1002',
							//'3_2'=>'1021',
							'4_1'=>'1005',
							//'4_2'=>'1022',
							//'5_2'=>'1023',
						);
						//VIP奖励
						$vipAward = array(
							'1_4'=>30,//奖励VIP30天
							'2_4'=>15,//奖励VIP15天
							'3_4'=>7,
							'4_4'=>3,
							'5_4'=>1,
						);
						//再来一次奖励
						$againAward = array(
							'1_2'=>'1',//可继续免费开金色箱子
							'2_2'=>'2',//可继续免费开银色箱子
							'3_2'=>'3',
							'4_2'=>'4',
							'5_2'=>'5',
						);
						
						
						//获取概率
						$myBoxRate = $boxAwardRate[$boxInfo['box_color']];
						$this->load->library('func');
						$awardNo = $this->func->dice($myBoxRate);
						/*if ($user_id==226){
							$awardNo = 1;
						}*/
						
						
						//奖品
						$award = $boxInfo['box_color'].'_'.$awardNo;
						//获取特定盒子的总积分
						$m_time = 0;
						if($boxInfo['miss_time'] > 0){
							$m_time = 1;
						}
						
						$speciallyTotalValue = $this->awardTotalArr($m_time);
						//获取特定盒子的金银铜铁木积分
						
						
						$speciallyValue = $this->awardArr($boxInfo['box_color'],$m_time);
						
						$color_num = $speciallyValue['credit_key'];
						$total_num = $speciallyTotalValue['credit_key'];
						
						$color_value = $speciallyValue['credit_value'];
						$total_value = $speciallyTotalValue['credit_value'];
						
						$num = '';

                        $award_message = '';
						if (isset($creditAward[$award])){
							//积分奖励
							$creditValue = rand($creditAward[$award][0], $creditAward[$award][1]);
							$creditValuemax = max($creditValue,$color_value,$total_value);
							
							if($total_value>$color_value && $total_value>$creditValue && $total_num!=0){
								$num = array('numtext'=>'总次数','number'=>$total_num);
							}else if($color_value>$creditValue && $color_value>$total_value && $color_num!=0){
								$num = array('numtext'=>$colorText[$boxInfo['box_color']].'宝箱','number'=>$color_num);							
							}
						
							
							$this->credit_init_data($user,$creditValuemax,$boxId,$result,$num);
                            $award_message = '积分奖励'.$creditValuemax;
							
						}elseif (isset($productAward[$award])){
							//商品奖励
							$pid = $productAward[$award];
							$shopPct = $this->Shop_model->getOne($pid);
							if($color_value > $shopPct['pcredit'] || $total_value>$shopPct['pcredit']){
								$creditValue = max($color_value,$total_value);
								if($total_value>$color_value && $total_num!=0){
									$num = array('numtext'=>'总次数','number'=>$total_num);
								}else{
									$num = array('numtext'=>$colorText[$boxInfo['box_color']].'宝箱','number'=>$color_num);	
								}
								$this->credit_init_data($user,$creditValue,$boxId,$result,$num);
							}else{
								$boxSetArr = array(
									'is_open' => 1,
									'award_type' => 2,
									'pid' => $pid,
								);
								
								$ret = $this->Shop_model->updateBox($boxSetArr,array('id'=>$boxId));
								if ($ret){
									//公告
									$mkey = 'box_notices';
									$notices = $this->mycache->get_array($mkey);
									$notice = "恭喜".$user['username']."打开".$colorText[$boxInfo['box_color']]."宝箱，获得奖励【".$productArr[$pid]."】";
									$notices[] = $notice;
									$this->mycache->set_array($mkey,$notices);
									
									$msg = "恭喜您获得奖励【".$productArr[$pid]."】，奖品1-3个工作日内发放";
                                    $award_message = '商品奖励'.$productArr[$pid];
									//echo $msg;
									$result['msg'] = $msg;
									$result['succ'] = 1;
								}else{
									//echo "数据错误";
									$result['msg'] = "数据错误";
								}
							}							
						}elseif (isset($vipAward[$award])){
							//VIP奖励
							$vipcreditValue = 50*188/356*$vipAward[$award];
							if($color_value > $vipcreditValue ||  $total_value>$vipcreditValue){
								$creditValue = max($color_value,$total_value);
								if($total_value>$color_value && $total_num!=0){
									$num = array('numtext'=>'总次数','number'=>$total_num);
								}else{
									$num = array('numtext'=>$colorText[$boxInfo['box_color']].'宝箱','number'=>$color_num);
								}
								$this->credit_init_data($user,$creditValue,$boxId,$result,$num);
							}else{
								$viptime = 3600*24*$vipAward[$award];//VIP奖励时间转成秒
								$this->load->model('User_vip_model');
								$vipinfo = $this->User_vip_model->get_by_uid($user_id);
								if ($vipinfo && $vipinfo['vip_status']==1 && $time-$vipinfo['vip_verify_time']<=3600*24*365){
									//本身是有效VIP，直接延期
									$vipSetArr = array(
										'vip_verify_time' => $vipinfo['vip_verify_time']+ $viptime
									);
									$this->User_vip_model->update($vipSetArr,array('user_id'=>$user_id));
								}elseif ($vipinfo && $vipinfo['vip_status']==1 && $time-$vipinfo['vip_verify_time']>3600*24*365){
									//已过期的  设置成奖励时间之后过期
									$vipSetArr = array(
										'vip_verify_time' => time()-(3600*24*365) + $viptime
									);
									$this->User_vip_model->update($vipSetArr,array('user_id'=>$user_id));
								}elseif (!$vipinfo){
									//不是VIP的 自动成为VIP 但是奖励时间过后过期
									$this->load->model('User_model');
									//$kefuList = $this->User_model->get_kefu_list();
									//$kefu_userid = array_rand($kefuList);//随机
									$kefu_userid = 0;//不随机  客户自选
									$verifyTime = time()-(3600*24*365)+$viptime;
									$vipSetArr = array(
										'user_id' => $user_id,
										'kefu_userid' => $kefu_userid,
										'kefu_addtime' => $verifyTime,
										'vip_status' => 1,//自动通过无需人工审核
										'vip_remark' => '',
										'vip_money' => 0,
										'vip_verify_remark' => 'VIP审核通过',
										'vip_verify_time' => $verifyTime,
									);
									$this->User_vip_model->apply($vipSetArr);
								}
								
								$boxSetArr = array(
									'is_open' => 1,
									'award_type' => 3,
									'vip_time' => $viptime,
									'fstatus' => 1
								);
								$ret = $this->Shop_model->updateBox($boxSetArr,array('id'=>$boxId));
								if ($ret){
									//公告
									$mkey = 'box_notices';
									$notices = $this->mycache->get_array($mkey);
									$notice = "恭喜".$user['username']."打开".$colorText[$boxInfo['box_color']]."宝箱，获得【VIP会员".$vipAward[$award]."天】";
									$notices[] = $notice;
									$this->mycache->set_array($mkey,$notices);
									
									$msg = "恭喜您获得奖励 德益投资VIP会员（".$vipAward[$award]."天）";
                                    $award_message = 'VIP奖励'.$vipAward[$award].'天';
									//echo $msg;
									$result['msg'] = $msg;
									$result['succ'] = 1;
								}else{
									//echo '数据错误';
									$result['msg'] = '数据错误';
								}
							}							
							
						}elseif (isset($againAward[$award])){
							//再来一次奖励
							$boxSetArr = array(
								'is_open' => 1,
								'award_type' => 4,
								'miss_time' => time()+3600*24,
								'fstatus' => 0
							);
							$ret = $this->Shop_model->updateBox($boxSetArr,array('id'=>$boxId));
							if ($ret){
								$msg = "恭喜您获得".$colorText[$boxInfo['box_color']]."宝盒钥匙一个，可免积分再次打开".$colorText[$boxInfo['box_color']]."宝盒一次，是否使用？";
								//echo $msg;
								$result['msg'] = $msg;
								$result['succ'] = 1;
								$result['data'] = $boxId;
								echo json_encode($result);
								exit;
							}else{
								$result['msg'] = '数据错误';
								echo json_encode($result);
								exit;
							}
						}else{
							$boxSetArr = array(
								'is_open' => 1,
								'award_type' => 0,
								'fstatus' => 1
							);
							$ret = $this->Shop_model->updateBox($boxSetArr,array('id'=>$boxId));
							$result['msg'] = '还差一点，再接再厉！';
							echo json_encode($result);
							exit;
						}

                        //发送积分抽奖成功站内信
                        $this->load->model("Message_model");
                        $this->Message_model->send(array('sent_user' => 1, 'receive_user' => $user_id,
                            'name' => "恭喜您抽到{$award_message},祝您生活愉快！",
                            'fstatus' => 0,
                            'message_type' => 'system',
                            'sented' => 0,
                            'deltype' => 0,
                            'content' => "恭喜您抽到{$award_message},祝您生活愉快！【华银资本】",
                            'add_time' => time(),
                            'addip' => $this->js->get_ip()
                        ));

                        echo json_encode($result);
                        exit;

						
					}
					
				}else{
					echo "数据错误";
					exit;
				}
			}else{
				echo "数据错误";
				exit;
			}
		}else{
			echo "请先登录";
			exit;
		}
	}
	
	function awardTotalArr($time){
		$speciallyAward = array(
			8=>'38',
			18=>'88',
			68=>'98',
			88=>'108',
			118=>'158',
			168=>'588',
			188=>'888',
			288=>'1088',
			388=>'1188',
			588=>'1588',
			888=>'1888',
			1188=>'2288',
			1588=>'5888',
			1888=>'8888',
		);
		
		$this->load->model('Shop_model');
			//$strtime = date('2014-4-28 10:00:00');
			$strtime = date('Y-m-d')." 00:00:00";
			$boxdata['where'] = array('strtime'=>$strtime,'is_open'=>1);
			$boxlist = $this->Shop_model->getBoxList($boxdata);
			if($time>0){
				$num = intval($boxlist['count']);
			}else{
				$num = intval($boxlist['count']+1);
			}
			
			$credit_value = 0;
			$credit_key = 0;
			
			foreach($speciallyAward as $nk=>$nval){
				if($num==$nk){
					$credit_key = $nk;
					$credit_value = $nval;
					break;
				}
			}
			$data = array('credit_key'=>$credit_key,'credit_value'=>$credit_value);
			return $data; 
	}
	
	function awardArr($box_color,$time){
			$speciallyAward = array(
				1=>array(
					8=>'2588',
					18=>'2688',
					28=>'2788',
					38=>'2888',
					48=>'2988',
					58=>'3088',
					68=>'4288',
					78=>'5388',
					88=>'6888',
				),
				2=>array(
					8=>'1588',
					18=>'1688',
					28=>'1788',
					38=>'1888',
					48=>'1988',
					58=>'2088',
					68=>'3388',
					78=>'3688',
					88=>'3888',
				),
				3=>array(
					8=>'888',
					18=>'988',
					28=>'1088',
					38=>'1188',
					48=>'1288',
					58=>'1388',
					68=>'1588',
					78=>'1688',
					88=>'1888',
				),
				4=>array(
					8=>'588',
					18=>'598',
					28=>'608',
					38=>'618',
					48=>'628',
					58=>'638',
					68=>'808',
					78=>'868',
					88=>'888',
				),
				5=>array(
					8=>'36',
					18=>'36',
					28=>'36',
					38=>'36',
					48=>'36',
					58=>'38',
					68=>'40',
					78=>'42',
					88=>'48',
					98=>'68',
					108=>'88',
				)
			);
			
			$this->load->model('Shop_model');
			//$strtime = date('2014-4-28 10:00:00');
			$strtime = date('Y-m-d')." 00:00:00";
			$boxdata['where'] = array('box_color'=>$box_color,'strtime'=>$strtime,'is_open'=>1);
			$boxlist = $this->Shop_model->getBoxList($boxdata);
			
			if($time>0){
				$num = intval($boxlist['count']);
			}else{
				$num = intval($boxlist['count']+1);
			}
			
			$credit_value = 0;
			$credit_key = 0;
			foreach($speciallyAward[$box_color] as $nk=>$nval){
				if($num==$nk){
					$credit_key  = $nk;
					$credit_value = $nval;
					break;
				}
			}
			$data = array('credit_key'=>$credit_key,'credit_value'=>$credit_value);
			return $data; 
		}
		
		function credit_init_data($user,$creditValue,$boxId,$result,$num){
			$this->load->model('Shop_model');
			$this->load->model('Credit_model', 'credit');
				
			$log = array(
				'user_id' => $user['user_id'],
				'type_id' => 15,
				'op' => 1,
				'credit_value' => $creditValue,
				'remark' => '商城抽奖积分增加'.$creditValue.'分',
				'op_user' => 1,
				'add_time' => time(),
				'addip' => '',
			);
			$this->credit->incr_credit($log);
			
			$is_specific_num = 0;
			$specific_text = '';
			 if(isset($num) && is_array($num) && count($num)>0){
				$is_specific_num = $num['number'];
				$specific_text = $num['numtext'];
			}
			
			$boxSetArr = array(
				'is_open' => 1,
				'award_type' => 1,
				'credit_value' => $creditValue,
				'fstatus' => 1,
				'is_specific_num' =>$is_specific_num,
				'specific_text' => $specific_text,
			);
			$ret = $this->Shop_model->updateBox($boxSetArr,array('id'=>$boxId));
						
			if($ret){
				 if(isset($num) && is_array($num) && count($num)>0){
					$mkey = "box_specific".date('Ymd');
					$notices = $this->mycache->get_array($mkey);
					$msgnum = $num['numtext'].'第'.$num['number'].'次奖励';	
					$notice = "恭喜".$user['username']."获得".$msgnum.$creditValue."分";
					$notices[] = $notice;
					$this->mycache->set_array($mkey,$notices);					
					$msg = "恭喜您获得".$msgnum.$creditValue."分";
				}else{
					$msg = "恭喜您获得".$creditValue."积分奖励";
				}
								
				//echo $msg;
				$result['msg'] = $msg;
				$result['succ'] = 1;
				echo json_encode($result);
				exit;
			}else{
				//echo "数据错误";
				$result['msg'] = "数据错误";
				echo json_encode($result);
				exit;
			}
		}
	
	function shop_synchronize(){
		$response_html = '';
		$this->load->model('Shop_model');
		$total_num = array(8,18,68,88,118,168,188,288,388,588,888,1188,1588,1888);
		$color_text = array(1=>array('color_box'=>'金盆','color_num'=>array(8,18,28,38,48,58,68,78,88)),
							2=>array('color_box'=>'银盆','color_num'=>array(8,18,28,38,48,58,68,78,88)),
							3=>array('color_box'=>'铜盆','color_num'=>array(8,18,28,38,48,58,68,78,88)),
							4=>array('color_box'=>'铁盆','color_num'=>array(8,18,28,38,48,58,68,78,88)),
							5=>array('color_box'=>'木盆','color_num'=>array(8,18,28,38,48,58,68,78,88,98,108)),
						);

		//$strtime = date('2014-4-28 10:00:00');
		$strtime = date('Y-m-d')." 00:00:00";
		$boxdata['where'] = array('is_open'=>1,'strtime'=>$strtime);
		
		$boxlist = $this->Shop_model->getBoxList($boxdata);
		$total = $boxlist['count'];
			
		$totaltimedistance = 0;
		for ($k=0;$k<strlen($total);$k++){
			$newtotal.="<img src='/static/ztimages/chou".substr($total,$k,1).".png' />";
		}
				
		for($i=0;$i<count($total_num);$i++){
			if($total<$total_num[$i]){
				$totaltimedistance = intval($total_num[$i]-$total);
				break;
			}
		}
		
		$last_total_num = end($total_num);
		
		$strlen = strlen($totaltimedistance);

		if($total>= $last_total_num){
			$newnum.="<img src='/static/ztimages/chou_why.png' />";
		}else{
			for ($j=0;$j<$strlen;$j++){
				$newnum.="<img src='/static/ztimages/chou".substr($totaltimedistance,$j,1).".png' />";
			}
		}

		$response_html .='<tr><td bgcolor="#fec776">总次数</td><td bgcolor="#fec776">'.$newtotal.'</td><td bgcolor="#fec776">'.$newnum.'</td></tr>';
		
		for($i=1;$i<6;$i++){
			$colordata['where'] = array('box_color'=>$i,'is_open'=>1,'strtime'=>$strtime);
			$color = $this->Shop_model->getBoxList($colordata);
			$colorlist[$i] = $color['count'];
		}
		
		$color_box = $colorlist;
		$index=1;
		foreach ($color_box as $k=>$val){
				$timenum = '';
				
				for ($z=0;$z<strlen($val);$z++){
					$timenum.="<img src='/static/ztimages/chou".substr($val,$z,1).".png' />";
				}
										
				$color_num = $color_text[$k]['color_num'];
				$last_color_num = end($color_num);
				$timedistance = 0;
				$timenewnum = '';
				if($val >= $last_color_num){
					$timenewnum.="<img src='/static/ztimages/chou_why.png' />";
				}else{
					for($i=0;$i<count($color_num);$i++){
						if($val<$color_num[$i]){
							$timedistance = intval($color_num[$i]-$val);
							$timestrlen = strlen($timedistance);
							for ($j=0;$j<$timestrlen;$j++){
								$timenewnum.="<img src='/static/ztimages/chou".substr($timedistance,$j,1).".png' />";
							}
							break;
						}
					}
				}
				if($index%2==0){
					$bgcolor = '#fec776';
				}else{
					$bgcolor = '#FFFFFF';
				}
		
				$response_html.='<tr><td bgcolor="'.$bgcolor.'">'.$color_text[$k]['color_box'].'</td><td bgcolor="'.$bgcolor.'">'.$timenum.'</td><td bgcolor="'.$bgcolor.'">'.$timenewnum.'</td></tr>';
				$index++;
			 }
			
			echo $response_html;
			exit;
		}
		
		function award_synchronize(){
			$response_html='';
			$specific_list = $this->award_cache();
			$specific_size = count($specific_list);
			if($specific_size>0){
				for ($i=0;$i<$specific_size;$i++){
					$response_html .= '<li>'.$specific_list[$i].'</li>';
				}
			}
			echo $response_html;
			exit;
		}
		
		function award_cache(){
			$this->load->model('Shop_model');
			$this->load->model('User_model');
			$mkey = "box_specific".date('Ymd');
			$specific_list = $this->mycache->get_array($mkey);
			
			if($specific_list == false){
				//$strtime = date('2014-4-28 10:00:00');
				$strtime = date('Y-m-d')." 00:00:00";
				$boxdata['where'] = array('is_open'=>1,'is_specific'=>1,'strtime'=>$strtime);
				$vboxlist = $this->Shop_model->count_shop_box_award($boxdata);
				foreach ($vboxlist['list'] as $val){
					$user = $this->User_model->get_by_uid($val['user_id']);
					$notice = "恭喜".$user['username']."获得".$val['specific_text'].'第'.$val['is_specific_num'].'次奖励'.$val['credit_value']."分";
					$specific_list[] = $notice;
				}
				$this->mycache->set_array($mkey,$specific_list);
			}
			return $specific_list;
		}
    function credit_detail(){
        $user = $this->session->userdata('zjy_user');
        $data = array();
        $per_page = intval($this->input->get('per_page'));//intval($page);
        $page_size = 15;
        $this->load->model('credit_model');
        $parms     = array(
            'user_id'   => intval($user['user_id'])
        );
        $resData = $this->credit_model->get_credit_log_list($parms,$per_page,$page_size,$limit = false);

        $data['list'] = $resData['list'];
        $this->load->library('pagination');
        $config['base_url'] = '/shop/credit_detail.html?start_time='.$parms['where']['strtime'].'&end_time='.$parms['where']['endtime'].'&type='.$parms['where']['ftype'];
        $config['total_rows'] = $resData['count'];
        $config['per_page'] = $page_size;
        //$config['page_query_string'] = false;
        $config['first_link'] = '首页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);
        $data['username'] = $user['username'];
        $data['where'] = $parms['where'];
        $data['title'] = "积分明细".' - '.CON_KEYWORDS;
        $data['tab_first'] = 'shop';
        $data['tab_second'] = 'shop_creditDetail';
        $this->load->view('/shop/credit_detail', $data);
    }

    function credit_exchange(){
        $user = $this->session->userdata('zjy_user');

        $data = array();

        $per_page = intval($this->input->get('per_page'));//intval($page);
        $page_size = 15;
        $pdata = array(
            'page' => $per_page,
            'page_size' => $page_size,
            'where' => array(
                'user_id' => intval($user['user_id'])
            )
        );
        $this->load->model('Shop_model');

        $resData = $this->Shop_model->orderPageList($pdata);

        $data['list'] = $resData['list'];
        $this->load->library('pagination');
        $config['base_url'] = '/shop/credit_exchange.html?start_time='.$pdata['where']['username'].'&pid='.$pdata['where']['pid'].'&fstatus='.$pdata['where']['fstatus'].'&strtime='.$pdata['where']['strtime'].'&endtime='.$pdata['where']['endtime'];
        $config['total_rows'] = $resData['count'];
        $config['per_page'] = $page_size;
        //$config['page_query_string'] = false;
        $config['first_link'] = '首页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['vars'] = $this->Shop_model->arrays();
        $data['statusArr'] = array(0=>'未发货',1=>'已发货');
        $data['username'] = $user['username'];
        $data['title'] = "积分兑换".' - '.CON_KEYWORDS;
        $data['tab_first'] = 'shop';
        $data['tab_second'] = 'shop_creditExchange';
        $this->load->view('/shop/credit_exchange', $data);
    }

    function credit_box(){
        $user = $this->session->userdata('zjy_user');

        $data = array();

        $per_page = intval($this->input->get('per_page'));//intval($page);
        $page_size = 15;
        $pdata = array(
            'page' => $per_page,
            'page_size' => $page_size,
            'where' => array(
                'user_id' => intval($user['user_id'])
            )
        );
        $this->load->model('Shop_model');

        $resData = $this->Shop_model->getBoxList($pdata);

        $data['list'] = $resData['list'];
        $this->load->library('pagination');
        $config['base_url'] = '/shop/credit_box.html?start_time='.$pdata['where']['username'].'&pid='.$pdata['where']['pid'].'&fstatus='.$pdata['where']['fstatus'].'&strtime='.$pdata['where']['strtime'].'&endtime='.$pdata['where']['endtime'];
        $config['total_rows'] = $resData['count'];
        $config['per_page'] = $page_size;
        //$config['page_query_string'] = false;
        $config['first_link'] = '首页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['vars'] = $this->Shop_model->arrays();
        $data['statusArr'] = array(0=>'未打开',1=>'已打开');
        $data['username'] = $user['username'];
        $data['title'] = "积分兑换".' - '.CON_KEYWORDS;
        $data['tab_first'] = 'shop';
        $data['tab_second'] = 'shop_box';
        $this->load->view('/shop/credit_box', $data);
    }
}
